<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php


class MMetadataController
extends MApplicationComponent
implements MIController
{
    private $_root      = null;
    private $_user_id   = null;
    private $_locale    = null;
    
    public function invoke($uri=null)
    {
                                parent::init();
        $params = $_REQUEST;
                if (isset($params) === false || $params == null) {
            throw new MAuthorizationException(FXP::t('Invalid parameters'));
        }
                        $user   = MUserManager::getInstance()->getCurrentUser();
        $this->_user_id     = $user->user_id;
        
        $list               = true;
        if (isset($params["list"])) {
            $list = $params["list"];
        }
        $file_limit         = 10000;
        if (isset($params["file_limit"])) {
            $file_limit     = $params["file_limit"];
        }
        $hash               = "";
        if (isset($params["hash"])) {
            $hash           = $params["hash"];
        }
        $include_deleted    = false;         if (isset($params["include_deleted"])) {
            $include_deleted = $params["include_deleted"];
        }
        $this->_locale      = "bytes";
        if (isset($params["locale"])) {
            $this->_locale  = $params["locale"];
        }
        
        $list               = MUtils::convertToBool($list);
        $include_deleted    = MUtils::convertToBool($include_deleted);
        
        $url                = $uri;
        $url                = parse_url($url, PHP_URL_PATH);
        $parts              = array_slice(explode('/', $url), 2);
        $this->_root        = $parts[0];
        
        $path               = null;
        foreach ($parts as $key => $name)
        {
            if ($key===0)
            {
                                continue;
            }
            $path .= "/{$name}";
        }
                                if ($pos = strpos($this->_root, '?'))
        {
            $this->_root = substr($this->_root, 0, $pos);
        }
        if ($pos = strpos($path, '?'))
        {
            $path = substr($path, 0, $pos);
        }
        
                if ($path == "" || $path == "/")
        {
            $response = $this->handeRootPath($list, $file_limit, $include_deleted);
        }
        else
        {
            $path               = "/{$this->_user_id}{$path}";
            $response = $this->handeNotRootPath(
                                                $path, 
                                                $list, 
                                                $file_limit, 
                                                $include_deleted);
        }
        echo json_encode($response);
    }

    
    private function  handeRootPath($list, $file_limit, $include_deleted)
    {
        $response = array();
        
        $response["size"]                   = MUtils::getSizeByLocale($this->_locale, 0);
        $response["bytes"]                  = 0;
        $response["path"]                   = "/";
        $response["modified"]               = MUtils::formatIntTime(time());
        $response["revision"]               = 0;
        $response["rev"]                    = "0";
        $response["root"]                   = $this->_root;
        $response["is_deleted"]             = false;
        $response["is_dir"]                 = true;
        $response["hash"]                   = "";
        $response["event"]                  = "0";
        if ($list == false)
        {
            $contents = array();
            $response["contents"] = $contents;
            return $response;
        }
        $query_db_file = MFiles::queryChildrenFilesByParentFileID(
                                                              $parent_file_id=0,
                                                              $include_deleted, 
                                                              $this->_user_id);
        if ($query_db_file === false || empty($query_db_file))
        {
            $contents = array();
            $response["contents"] = $contents;
            return $response;
        }
                                $contents = array();
        foreach ($query_db_file as $key => $db_file)
        {
            $content = array();
            $query_version_file = MFileVersions::queryFileVersionByID($db_file["version_id"]);
            $mime_type = null;
            $signature = null;
            if ($query_version_file)
            {
                $mime_type = $query_version_file[0]["mime_type"];
                $signature = $query_version_file[0]["file_signature"];
            }
            $db_file["signature"] = $signature;
            $content = $this->assembleResponse($content, $db_file, $mime_type);
            array_push($contents, $content);
        }
        $response["contents"] = $contents;
        return $response;
    }
    
    
    private function handeNotRootPath($path, $list, $file_limit, $include_deleted)
    {
                                if ($include_deleted)
        {
            $query_db_file = MFiles::queryAllFilesByPath($path);
        }
        else 
        {
            $query_db_file = MFiles::queryFilesByPath($path);
        }
        if ($query_db_file == false || empty($query_db_file))
        {
            throw new MFileopsException(
                                        FXP::t('not existed'),
                                        MConst::HTTP_CODE_404);
        }
                                $query_version_file = MFileVersions::queryFileVersionByID($query_db_file[0]["version_id"]);
        $mime_type = null;
        if ($query_version_file)
        {
            $query_db_file[0]["signature"] = $query_version_file[0]["file_signature"];
            $mime_type = $query_version_file[0]["mime_type"];
        }
        $response                   = array();
        $response = $this->assembleResponse($response, $query_db_file[0], $mime_type);
        if ($list == true && $query_db_file[0]["file_type"] == MConst::OBJECT_TYPE_DIRECTORY)
        {
                                                $children_db_files = MFiles::queryChildrenFilesByParentFileID(
                                    $query_db_file[0]['id'], $include_deleted);
                                                if (count($children_db_files) > $file_limit)
            {
                throw new MFileopsException(
                            FXP::t('Too many file'),
                            MConst::HTTP_CODE_406);
            }
                                                $contents = array();
            foreach ($children_db_files as $key => $db_file)
            {
                $content = array();
                $query_version_file = MFileVersions::queryFileVersionByID($db_file["version_id"]);
                $mime_type = null;
                if ($query_version_file)
                {
                    $mime_type = $query_version_file[0]["mime_type"];
                    $db_file["signature"] = $query_version_file[0]["file_signature"];
                }
                $content = $this->assembleResponse($content, $db_file, $mime_type);
                array_push($contents, $content);
            }
            $response["contents"] = $contents;
        }
        return $response;
    }
    
    
    private function assembleResponse($response, $file_detail, $mime_type)
    {
        $file_path                          = $file_detail["file_path"];
        $index                              = strlen("/{$this->_user_id}");
        $file_path                          = substr_replace($file_path,"",0, $index);
        $response["size"]                   = MUtils::getSizeByLocale($this->_locale, $file_detail["file_size"]);
        $response["bytes"]                  = (int)$file_detail["file_size"];
        $response["path"]                   = $file_path;
        $response["modified"]               = MUtils::formatIntTime($file_detail["file_update_time"]);
        $response["revision"]               = intval($file_detail["version_id"]);
        $response["rev"]                    = strval($file_detail["version_id"]);
        $response["root"]                   = $this->_root;
        $response["hash"]                   = isset($file_detail["signature"])? $file_detail["signature"] : "";
        $response["event"]                  = $file_detail["event_uuid"];
        $is_dir = true;
        
        if ($file_detail["file_type"] == MConst::OBJECT_TYPE_FILE)
        {
            $response["thumb_exists"]       = MUtils::isExistThumbnail($mime_type, (int)$file_detail["file_size"]);
            $is_dir = false;
        }
        $response["is_dir"]                 = $is_dir;
        if (!empty($mime_type))
        {
            $response["mime_type"]          = $mime_type;
        }
        if ($file_detail["is_deleted"] == true)
        {
            $response["is_deleted"]        = true;
        }
        return $response;
    }
}
?>